<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="format-detection" content="telephone=no,email=no" />
		<title>购物车提交订单页</title>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link href="css/style.css" rel="stylesheet" />
	</head>
	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title">提交订单</h1>
		</header>
		<div id="scrollDiv" class="scroll-div">
			<div class="mui-content transparent">
				<div id="orderSubmit" class="order-submit"></div>
			</div>
		</div>
		<div class="cart-bottom transparent">
			<p class="order-price-total">共<em id="OrderCount">0</em>件，总金额<span id="OrderAmount"></span></p>
			<a class="submit-cart" id="submitBtn">提交订单</a>
		</div>
		<div id="dcontent" class="dcontent"></div>
		<div id="payWayBox" class="screen-box">
        	<div class="screen-list" id="payWayTeam"></div>
        	<div class="screen-enter">
        		<a class="custom-btn" id="payWayChoose">确 定</a>
        	</div>
        </div>
		<div id="invoiceBox" class="screen-box">
			<div class="screen-list" id="invoiceTeam"></div>
        	<div class="screen-enter">
        		<a class="custom-btn" id="invoiceChoose">确 定</a>
        	</div>
        </div>
        
		<script src="js/mui.min.js"></script>
		<script src="js/delayimg.min.js"></script>
		<script src="js/app.js"></script>
		<script>
			mui.init({swipeBack: true});
			var cartItemId,
				skuIdCount,
				fightGroup,
				orderData,
				orderUrl,
				integral=0,
				couponIds=[],
				isCashOnDelivery=false,
				invoiceType=0,
				invoiceContext,
				invoiceTitle,
				pays={},
				mask,
				payOrderId,
				usePayWayText,
				loadPage,
				ws;
			mui.plusReady(function() {
				ws=plus.webview.currentWebview();
				cartItemId=ws.cartItemId;
				skuIdCount=ws.skuIdCount;
				fightGroup=ws.fightGroup;
				var w=plus.nativeUI.showWaiting('',{padlock:true});
				if(cartItemId){
					orderData={cartItemIds:cartItemId};
					orderUrl='api/Order/GetSubmitByCartModel';
				}else if(skuIdCount){
					orderData=JSON.parse(skuIdCount);
					orderUrl='api/Order/GetSubmitModel';
				}else if(fightGroup){
					orderData=JSON.parse(fightGroup);
					orderUrl='api/Order/GetGroupOrderModel';
				}
				loadPage=function(){
					mui.ajax(URL+orderUrl,{
						dataType:'json',
						data:orderData,
						type:'get',
						timeout:10000,
						success:function(data){ 
							var html='';
							if(data.Address!=null){ 
								html+='<ul class="mui-table-view mui-table-view-chevron address-list" id="addressList" data-id="'+data.Address.AddrId+'">'+
									'<li class="mui-table-view-cell">'+
										'<a class="mui-navigate-right">'+
											'<p><span>'+data.Address.ShipTo+'</span>'+data.Address.Phone+'</p>'+
											'<p><i class="mui-icon mui-icon-location"></i><span>'+data.Address.Address+'</span></p>'+
											'<i class="mui-icon mui-icon-arrowright icon-right"></i>'+
										'</a>'+
									'</li>'+
								'</ul>';
							}else{
								html+='<ul class="mui-table-view mui-table-view-chevron address-list" id="addressList">'+
									'<li class="mui-table-view-cell">'+
										'<a class="mui-navigate-right">'+
											'<p>暂未添加您的专属收货地址，去设置</p>'+
											'<i class="mui-icon mui-icon-arrowright icon-right" style="top:0"></i>'+
										'</a>'+
									'</li>'+
								'</ul>';
							}
							html+='<div class="order-info">'+
								'<div class="item">'+
									'<div class="item-choose" id="usePayWay">'+
									    '<span>支付方式</span>'+
									    '<div class="mui-pull-right"><em id="usePayWayText">在线支付</em><i class="mui-icon mui-icon-arrowright icon-right"></i></div>'+
									'</div>'+
								'</div>'+
							'</div>';
							 
							var payWay=false,
								onlineCodPay='',
								onlinePay='';
								
							for(var i=0;i<data.ShopCartItem.length;i++){
					            html+='<div class="order-info">'+
									'<div class="item">'+
										'<div class="order-shop">'+
											'<a class="vshop-url" data-id="'+data.ShopCartItem[i].vshopId+'"><i class="iconfont icon-dianpu"></i>'+data.ShopCartItem[i].ShopName+'</a>'+
										'</div>'+
									'</div>';
					            	for(var j=0;j<data.ShopCartItem[i].CartItemModels.length;j++){
						                html+='<div class="item" data-skuid="'+data.ShopCartItem[i].CartItemModels[j].skuId+'">'+
						                    '<div class="buy-goods">'+
						                        '<a class="goods-url goods-img" data-id="'+data.ShopCartItem[i].CartItemModels[j].id+'"><img src="images/blank.gif" data-delay="'+data.ShopCartItem[i].CartItemModels[j].imgUrl+'"/></a>'+
						                        '<p><em>¥ '+data.ShopCartItem[i].CartItemModels[j].price+'</em><span><a class="goods-url" data-id="'+data.ShopCartItem[i].CartItemModels[j].id+'">'+data.ShopCartItem[i].CartItemModels[j].name+'</a></span></p>'+
						                        '<h5><span>x '+data.ShopCartItem[i].CartItemModels[j].count+'</span>';
						                        	if(data.ShopCartItem[i].CartItemModels[j].size)
														html += '尺寸：'+data.ShopCartItem[i].CartItemModels[j].size+'&nbsp;&nbsp;';
													if(data.ShopCartItem[i].CartItemModels[j].color)
														html += '颜色：'+data.ShopCartItem[i].CartItemModels[j].color+'&nbsp;&nbsp;';
													if(data.ShopCartItem[i].CartItemModels[j].version)
														html += '规格：'+data.ShopCartItem[i].CartItemModels[j].version;
						                            html+='</h5>'+
						                    '</div>'+
						                '</div>';
						                if(data.ShopCartItem[i].CartItemModels[j].IsSelf){
						                	onlineCodPay+='<li><img src="'+data.ShopCartItem[i].CartItemModels[j].imgUrl+'"></li>';
						                }else{
						                	onlinePay+='<li><img src="'+data.ShopCartItem[i].CartItemModels[j].imgUrl+'"></li>';
						                }
					               	}
					                if(data.ShopCartItem[i].Coupon!=null && !fightGroup){
										couponIds.push(data.ShopCartItem[i].Coupon.Id+'_'+data.ShopCartItem[i].Coupon.BaseType);
										html+='<div class="item">'+
							                '<div class="item-text">'+
							                '<span>优惠券</span>'+
							                '<span class="mui-pull-right">抵扣 &nbsp;'+data.ShopCartItem[i].Coupon.BasePrice+'元</span></div>'+
							            '</div>';
									}
						            html+='<div class="item">'+
						                '<div class="item-text">'+
						                '<span>配送方式</span>';
						                if(data.ShopCartItem[i].isFreeFreight)
						                	html+='<span class="mui-pull-right">快递 &nbsp;免邮</span></div>';
						                else
						                	html+='<span class="mui-pull-right">快递 &nbsp;'+data.ShopCartItem[i].Freight+'元</span></div>';
						            html+='</div>'+
						            '<div class="item total-m">';
						            if(data.ShopCartItem[i].IsSelf){
										payWay=true;
										html+='<span class="pay-way-notice" id="selfPayWay">在线支付</span>';
										if(!fightGroup){
											html+='<span class="mui-pull-right total">微店合计<em id="selfAmout">¥ '+data.ShopCartItem[i].OrderAmount+'</em></span>';
										}
									}else{
										html+='<span class="pay-way-notice">在线支付</span>';
										if(!fightGroup){
											html+='<span class="mui-pull-right total">微店合计<em>¥ '+data.ShopCartItem[i].OrderAmount+'</em></span>';
										}
									}
						            html+='</div>'+
						        '</div>';
					       	}
							
							 
							if(!fightGroup){
						        html+='<div class="order-info">'+
									'<div class="item">'+
										'<div class="item-score">'+
										    '<span>可用'+data.UserIntegrals+'积分抵扣<em>¥'+data.IntegralPerMoney+'</em></span>'+
										    '<div id="useIntegral" data-score="'+data.UserIntegrals+'" class="mui-switch mui-pull-right"><div class="mui-switch-handle"></div></div>'+
										'</div>'+
									'</div>'+
								'</div>';
							}
							html+='<div class="order-info">'+
								'<div class="item">'+
									'<div class="item-choose" id="useInvoice">'+
									    '<span>发票信息</span>'+
									    '<div class="mui-pull-right"><em id="useInvoiceText">不需要发票</em><i class="mui-icon mui-icon-arrowright icon-right"></i></div>'+
									'</div>'+
								'</div>'+
							'</div>';
							var invoiceHtml='<h3>发票内容</h3><ul class="mui-table-view">';
							for(var j=0; j<data.InvoiceContext.length; j++){
								invoiceHtml+='<li class="mui-table-view-cell mui-radio mui-left"><input name="invCon" type="radio" data-name="'+data.InvoiceContext[j].Name+'" />'+data.InvoiceContext[j].Name+'</li>';
							}
							invoiceHtml+='</ul>';
							document.getElementById('invoiceTeam').innerHTML='<h3>发票抬头</h3><ul class="mui-table-view">'+
								'<li class="mui-table-view-cell mui-radio mui-left"><input name="invHead" type="radio"/>个人</li>'+
								'<li class="mui-table-view-cell mui-radio mui-left"><input name="invHead" type="radio"/>公司<input class="invoice-text" type="text" placeholder="公司全名"/></li>'+
							'</ul>'+invoiceHtml;
							
							//integral=data.UserIntegrals;
							document.getElementById('orderSubmit').innerHTML=html;
							var OrderAmount=document.getElementById('OrderAmount');
							usePayWayText=document.getElementById('usePayWayText');
							delayimg.init({content:document.getElementById('scrollDiv')});
							OrderAmount.innerText='¥ '+data.OrderAmount.toFixed(2);
							document.getElementById('OrderCount').innerText=document.getElementsByClassName('buy-goods').length;
							
							var maskPay,maskInv;
							document.getElementById('usePayWay').addEventListener('tap',function(){
								if(fightGroup){
									plus.nativeUI.toast('拼团订单只支持在线支付');
									return;
								}
								if(!data.IsCashOnDelivery){
									plus.nativeUI.toast('当前收货地址只支持在线支付');
								}else{
									if(!payWay){
										plus.nativeUI.toast('非官方自营店只支持在线支付');
									}else{
										if(document.getElementById('payWayTeam').innerText==''){
											if(onlineCodPay!='')
												document.getElementById('payWayTeam').insertAdjacentHTML('beforeend','<div class="payClass"><h3>支持在线支付和货到付款</h3><ul class="pay-way-goods">'+onlineCodPay+'</ul><div class="pay-choose" id="onlineCodChoose"><span class="cur">在线支付</span><span>货到付款</span></div></div>');
											if(onlinePay!='')
												document.getElementById('payWayTeam').insertAdjacentHTML('beforeend','<div class="payClass"><h3>仅支持在线支付</h3><ul class="pay-way-goods">'+onlinePay+'</ul><div class="pay-choose"><span class="cur">在线支付</span></div></div>');
										}
										openScreen(maskPay,'payWayBox');
									}
								}
								
							});
							
							mui('#payWayBox').on('tap','#onlineCodChoose span',function(){
								siblings(this)[0].className='';
								this.className='cur';
							})
							
							document.getElementById('useInvoice').addEventListener('tap',function(){
								openScreen(maskInv,'invoiceBox');
							});
							
							function openScreen(masks,box){
								document.getElementById(box).className='screen-box active';
								if(!masks)
									masks = mui.createMask(function(){document.getElementById(box).className='screen-box'});
								masks.show();
								
								if(box=='payWayBox'){
									mui('#payWayBox').off('tap','#payWayChoose');
									mui('#payWayBox').on('tap','#payWayChoose',function(){
										if(onlineCodPay!=''){
											var index=getIndex(document.getElementById('onlineCodChoose').getElementsByClassName('cur')[0]),
												selfPayWay=document.getElementById('selfPayWay');
											if(index==1 && onlinePay!=''){
												usePayWayText.innerText='在线支付+货到付款';
												selfPayWay.innerText='货到付款';
												isCashOnDelivery=true;
											}else if(index==0){
												usePayWayText.innerText=selfPayWay.innerText='在线支付';
												isCashOnDelivery=false;
											}else{
												usePayWayText.innerText=selfPayWay.innerText='货到付款';
												isCashOnDelivery=true;
											}
											
											masks.close();
											
										}
									});
								}
								if(box=='invoiceBox'){
									mui('#invoiceBox').off('tap','#invoiceChoose');
									mui('#invoiceBox').on('tap','#invoiceChoose',function(){
										var useInvoiceText=document.getElementById('useInvoiceText'),
											invHead=document.querySelector('input[name="invHead"]:checked'),
											invCon=document.querySelector('input[name="invCon"]:checked');
										
										if(!invHead || !invCon){
											useInvoiceText.innerText='不需要发票';
											invoiceContext=invoiceTitle=null;
											invoiceType=0;
										}else{
											var invHeadText=siblings(invHead,'input[type="text"]')[0];
											if(invHeadText){
												if(invHeadText.value==''){
													plus.nativeUI.toast('请填写公司全名');
													return false;
												}else{
													invoiceTitle=invHeadText.value;
												}
											}else{
												invoiceTitle='个人';
											}
											useInvoiceText.innerText=invoiceTitle;
											invoiceContext=invCon.getAttribute('data-name');
											invoiceType=2;
										}
										
										masks.close();
									});
								}
							}
							
							if(document.getElementById('useIntegral')){
								mui('#useIntegral').switch();
								mui('#orderSubmit').on('toggle','#useIntegral',function(event){
									if(data.UserIntegrals<1){
										plus.nativeUI.toast('积分抵扣使用积分少于1分，无法抵扣');
										return;
									}
									setTimeout(function() {
										if(event.detail.isActive){
											integral=data.UserIntegrals;
											OrderAmount.innerText='¥ '+(data.orderAmount-data.IntegralPerMoney).toFixed(2);
										}else{
											integral=0;
											OrderAmount.innerText='¥ '+data.orderAmount;
										}
									}, 50);
								});
							}
							plus.nativeUI.closeWaiting();
				            document.getElementsByClassName("mui-content")[0].className="mui-content";
				            document.getElementsByClassName("cart-bottom")[0].className="cart-bottom";
						},
						error:function(xhr,type,errorThrown){
							plus.nativeUI.closeWaiting();
							reloadWvLoad();
						}
					});
				}
				
				loadPage();
				initPay('dcontent');
			});
			
			mui('#orderSubmit').on('tap', '.goods-url', function() {
				var id = this.getAttribute('data-id');
				showProduct(id);
			});
			
			mui('#orderSubmit').on('tap', '.vshop-url', function() {
				var vshopid = this.getAttribute('data-id');
				if(vshopid==0){
					mui.toast('该店铺暂未开通微店')
				}else{
					showVshop(vshopid,'/');
				}
				
			});
			
			mui('#orderSubmit').on('tap', '#addressList', function() {
				himall.openVW('user/address.html','user/address.html',{orderTag:'orderTag'});
			});
			
			window.addEventListener('updateData',function(){
				isCashOnDelivery=false;
				invoiceType=0;
				invoiceContext='';
				invoiceTitle='';
				loadPage();
				
			});
			
			document.getElementById('submitBtn').addEventListener('tap',function(){
				var submitUrl,
					submitData,
					couponId=couponIds.join(','),
					recieveAddressId=document.getElementById('addressList').getAttribute('data-id');
					 
				if(!recieveAddressId){
					plus.nativeUI.toast('请设置收货地址');
					return false;
				}
				var w=plus.nativeUI.showWaiting('',{padlock:true});
				if(cartItemId){
					submitUrl='api/Order/PostSubmitOrderByCart';
					submitData={
						cartItemIds:cartItemId,
						recieveAddressId:recieveAddressId,
						couponIds:couponId,
						integral:integral,
						isCashOnDelivery:isCashOnDelivery,
						invoiceType:invoiceType,
						invoiceContext:invoiceContext,
						invoiceTitle:invoiceTitle
						
					};
				}else if(skuIdCount){
					submitUrl='api/Order/PostSubmitOrder';
					submitData={
						skuIds:orderData.skuId,
						counts:orderData.count,
						recieveAddressId:recieveAddressId,
						couponIds:couponId,
						integral:integral,
						isCashOnDelivery:isCashOnDelivery,
						invoiceType:invoiceType,
						invoiceContext:invoiceContext,
						invoiceTitle:invoiceTitle
					};
				}else if(fightGroup){
					submitUrl='api/Order/PostSubmitFightGroupOrder';
					submitData=mui.extend({
						recieveAddressId:recieveAddressId,
						isCashOnDelivery:isCashOnDelivery,
						invoiceType:invoiceType,
						invoiceContext:invoiceContext,
						invoiceTitle:invoiceTitle
					},orderData);
				}
				//alert(JSON.stringify(submitData));
				console.log("dd");
				mui.ajax(URL+submitUrl,{
					data:JSON.stringify(submitData),
					dataType:'json',
					contentType:'application/json',
					type:'POST',
					timeout:10000, 
					success:function(data){
						if(data.Success=="true"){
							plus.nativeUI.toast('订单已提交，请尽快付款');
							if(cartItemId){
								mui.fire(plus.webview.getWebviewById('cart.html'),'updateData');
							}	
							payOrderId=data.OrderIds.join(',');
							var lastAmount=parseFloat(document.getElementById('OrderAmount').innerText.replace('¥ ',''));
							if(lastAmount<=0){
								mui.ajax(URL+'api/Order/GetPayOrderByIntegral?orderIds='+payOrderId,{
									dataType:'json',
									type:'get',
									timeout:10000,
									success:function(data){
										if(data.Success=="true"){
											w.close();
											plus.nativeUI.alert('订单需支付金额为零，购买成功，等待发货',function(){
												openOrderList(2);
											});
											
										}else{
											w.close();
											plus.nativeUI.toast('订单支付失败，请稍后重试')
										}
									},
									error:function(xhr,type,errorThrown){
										w.close();
										plus.nativeUI.toast('订单支付失败，请检查网络')
									}
								});
								
							}else if(usePayWayText.innerText=='货到付款'){
								plus.nativeUI.alert('订单所有商品均为货到付款，等待发货',function(){
									openOrderList(2);
								});
							}else{
								w.close();
								if(isCashOnDelivery){
									document.getElementById('dcontent').insertAdjacentHTML('afterBegin','<p class="dcontent-text">在线支付<span><i>¥</i>'+(lastAmount-parseFloat(document.getElementById('selfAmout').innerText.replace('¥ ','')))+'</span></p>')
								}
								if(!mask)
									mask = mui.createMask(function(){
										document.getElementById('dcontent').className='dcontent';
										openOrderList(1);
									});
								mask.show();
								document.getElementById('dcontent').className='dcontent active';
							}
						}else{
							w.close();
							plus.nativeUI.alert(data.Msg);
						}
					},
					error:function(xhr,type,errorThrown){
						w.close();
						plus.nativeUI.toast('提交订单失败，请检查网络')
					}
				});
				
				
			});
			
			var wPay=null;
			mui('#dcontent').on('tap','.custom-btn',function(){
				payOrder(this.id,payOrderId,
					function(){
						plus.nativeUI.alert("支付成功，等待卖家发货！",function(){
							if(!fightGroup){
								openOrderList(2,payOrderId);
							}else{
								himall.openVW('merge-personal-list.html','marketing/merge-personal-list.html');
								setTimeout(function(){
									plus.webview.getWebviewById('order-submit.html').close('none');
								},1000)
								//himall.openVW('merge-call.html','marketing/merge-call.html',{shareData:JSON.parse(fightGroup).shareData});
							}
						});
					},function(){
						plus.nativeUI.alert("订单支付失败！",function(){
							openOrderList(1);
						});
					}
				)
			});
			
			function openOrderList(num,bonusId){
				himall.openVW('order-list.html','',{orderStatus:num,bonusId:bonusId});
				setTimeout(function(){
					plus.webview.getWebviewById('order-submit.html').close('none');
				},1000)
			}
			
		</script>
	</body>

</html>